<template>
<!--  <h2>项目阶段配置</h2>-->
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm"  :inline="true" v-show="showSearch">
      <el-form-item label="项目名称" prop="projectName">
        <el-input v-model="queryParams.projectName" placeholder="请输入项目名称" clearable style="width: 240px"
                  @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="工程代号" prop="projectCode">
        <el-input v-model="queryParams.projectCode" placeholder="请输入工程代号" clearable style="width: 240px"
                  @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="项目阶段" prop="projectPhase">
        <el-select v-model="queryParams.projectPhase" clearable placeholder="请选择" style="width: 100%">
          <el-option v-for="dict in dict.type.XMJD" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search"  @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh"  @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8" ref="refbut">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus"  @click="handleAdd" v-hasPermi="['zt:project:examples:save']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-edit"  @click="handleDelete" v-hasPermi="['zt:project:examples:delete']">删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-table v-loading="loading" :data="tableDataList" @selection-change="handleSelectionChange" :height="tableHeight" style="width: 100%;overflow: auto;">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" :index="table_index" width="55" align="center" prop="projectExamplesId"/>
      <el-table-column label="项目名称" prop="projectName" align="center" />
      <el-table-column label="工程代号" prop="projectCode" align="center" />
      <el-table-column label="项目阶段" prop="itemPhase" align="center" />
      <el-table-column label="所属生产院" prop="deptName" align="center" />
      <el-table-column label="阶段名称" prop="nodeName" align="center" width="150" />
      <el-table-column label="项目总体" prop="projectOverallName" align="center" />
      <el-table-column label="项目分类" prop="projectClassification" align="center" />
      <el-table-column label="专业" prop="major" align="center" width="200" />
      <el-table-column label="创建时间" prop="createTime" align="center" width="150" />
      <el-table-column label="操作" align="center" width="400">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" plain @click="settingStage(scope.row)" v-show="scope.row.status != '4'" v-hasPermi="['zt:project:examples:setup:phase']">设置阶段</el-button>
          <el-button type="success" size="mini" plain @click="settingMajors(scope.row)" v-show="scope.row.status != '4'" :disabled="scope.row.status=='0'" v-hasPermi="['zt:project:examples:setup:major']">设置专业</el-button>
          <el-button type="danger" size="mini" plain @click="settingPersonnel(scope.row)" v-show="scope.row.status != '4'" :disabled="scope.row.status=='0' || scope.row.status=='1'" v-hasPermi="['zt:project:examples:setup:user']">分配人员</el-button>
          <el-button type="warning" size="mini" plain @click="distributeTasks(scope.row)" v-show="scope.row.status == '4' || scope.row.status == '3'" :disabled="scope.row.status == '4'" v-hasPermi="['zt:project:examples:deliver:task']">下发任务</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

    <!-- 添加/修改文件 -->
    <el-dialog :title="itemTitle" :visible.sync="itemOpen" width="35%" append-to-body>
      <el-form ref="itemForm" :model="itemForm" :rules="itemRules" label-width="120px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="项目名称" prop="projectId">
              <el-select v-model="itemForm.projectId" filterable placeholder="请选择项目名称" clearable style="width: 100%;">
                <el-option v-for="item in itemNameOption" :key="item.PROJECTID" :label="item.PROJECTNAME" :value="item.PROJECTID">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitItemForm">保 存</el-button>
        <el-button  @click="itemCancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 设置阶段 -->
    <el-dialog :title="stageTitle" :visible.sync="stageOpen" width="30%" append-to-body>
      <el-input v-model="nodeName" placeholder="请输入名称" clearable size="small" prefix-icon="el-icon-search"
                style="margin-bottom: 20px" />
      <div style="overflow-y: auto; height: 350px">
        <el-tree ref="stageTree" :data="treeData" show-checkbox node-key="phaseId" :props="defaultProps" default-expand-all
                 @check-change="selectTreeNode" @check="treeCheck" :filter-node-method="filterNode">
        </el-tree>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitStage">确 定</el-button>
        <el-button @click="stageCancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 设置专业 -->
    <el-dialog :title="majorsTitle" :visible.sync="majorsOpen" width="30%" append-to-body>
      <el-form ref="majorsForm" :model="majorsForm" label-width="120px">
        <el-form-item label="专业名称：" prop="selectOption">
          <el-checkbox-group v-model="selectOption">
            <el-checkbox v-for="option in majorsOptions" :key="option.value" :label="option.value">
              {{ option.label }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitMajors">确 定</el-button>
        <el-button @click="majorsCancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 分配人员 -->
    <AssignPersonnel :title="allocationTitle" :open="allocationOpen" @closeDelDialog="closeDelDialog" ref="alloctionRef"></AssignPersonnel>
  </div>
</template>

<script>
import {
  addProject, deleteProject, deliverATask,
  getItemSelect,
  getMajors,
  getTableList, saveMajors,
  saveStage
} from "@/api/stage/stageManagement/phaseConfiguration";
import estimateTableHeight from "@/mixins/estimateTableHeight";
import {deptUserTree} from "@/api/archive/fileCollection/archiveApproval";
import {getByIdTree} from "@/api/stage/stageManagement/stageTemplate";
import AssignPersonnel from "@/views/stage/stageManagement/phaseConfiguration/assignPersonnel";

export default {
  name: "index",
  components: {AssignPersonnel},
  mixins: [ estimateTableHeight ], // 混入方法
  archive_Dicts: ['XMJD'],
  data() {
    return {
      queryParams: {
        pageNum:1,
        pageSize:10,
        projectName: undefined,
        projectCode: undefined,
        projectPhase: undefined
      },
      // 显示搜索条件
      showSearch: true,
      // 遮挡层
      loading: true,
      // 表格数据
      tableDataList: [],
      // 总条数
      total: 0,
      // 选中数组
      ids: [],
      detail: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,

      itemTitle: '',
      itemOpen: false,
      itemForm: {
        projectId: undefined
      },
      itemRules: {
        projectId: [
          { required: true, message: "项目名称不能为空", trigger: "blur" }
        ]
      },
      // 项目名称下拉
      itemNameOption: [],
      deptUserOptions: [],

      // 设置阶段
      stageTitle: '',
      stageOpen: false,
      // 设置阶段表单
      // 部门名称
      nodeName: undefined,
      stageForm: {},
      treeData: [],
      defaultProps: {
        children: "phasesVoList",
        label: "nodeName"
      },
      selectTreeOption: [],
      //默认展开的树节点
      expandedkeys: [],
      //默认选中的树节点
      currentNodekey: "",

      // 设置专业
      majorsTitle: '',
      majorsOpen: false,
      selectOption: [], // 选中的专业节点
      majorsOptions: [],
      majorsForm: {},

      // 分配人员
      allocationTitle: '',
      allocationOpen: false,
    }
  },
  created() {
    this.deptUserTreePost();
    this.getList();
    this.getOption();
  },
  watch: {
    // 根据名称筛选树
    nodeName(val) {
      console.log(val)
      this.$refs.stageTree.filter(val);
    },
  },
  methods: {
    // 获取项目下拉
    getOption() {
      getItemSelect().then(response=>{
        this.itemNameOption = response.data
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    getList() {
      this.loading = true
      getTableList(this.queryParams).then(response=>{
        this.loading = false
        this.tableDataList = response.rows
        for (let i = 0; i < response.rows.length; i++) {
          // this.tableDataList[i].itemOverall = this.getLabelById(response.rows[i].projectOverall)
          this.tableDataList[i].major = response.rows[i].majorList.map(item => item.majorName).toString()

          for (let j = 0; j < this.dict.type.XMJD.length; j++) {
            if(response.rows[i].projectPhase == this.dict.type.XMJD[j].value) {
              this.tableDataList[i].itemPhase = this.dict.type.XMJD[j].label
            }
          }
        }
        this.total = response.total
      })
    },
    // 根据id获取对应的名称
    getLabelById(id) {
      function recurse(nodes) {
        for (let node of nodes) {
          if(node.id == id) {
            return node.label
          }
          if (node.children) {
            const label = recurse(node.children)
            if (label) return label
          }
        }
      }
      return recurse(this.deptUserOptions)
    },
    /**获取人员树接口 */
    deptUserTreePost(){
      deptUserTree().then(response => {
        this.deptUserOptions = response.data;
        // 重命名树结构中的字段
        this.deptUserOptions.forEach(node => {
          this.appendUser(node);
        });
      });
    },
    appendUser(node) {
      if (node.children && node.children.length > 0) {
        node.children.forEach(child => {
          this.appendUser(child);
        });
      }
      if (node.userChildren && node.userChildren.length > 0) {
        node.children = [...(node.children || []), ...node.userChildren];
        delete node.userChildren;
      }
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!=1
      this.multiple = !selection.length
      this.detail = selection.map(item => {
        return {
          projectExamplesId: item.projectExamplesId,
          majorList: item.majorList
        }
      })
    },
    table_index(index){
      return (this.queryParams.pageNum-1) * this.queryParams.pageSize + index + 1;
    },
    // 新增
    handleAdd() {
      this.itemForm.projectId = undefined
      this.itemOpen = true
      this.itemTitle = '添加项目'
    },
    submitItemForm() {
      this.$refs["itemForm"].validate(valid => {
        if(valid) {
          addProject(this.itemForm).then(response=>{
            this.$modal.msgSuccess('新增成功')
            this.itemOpen = false
            this.getList()
          })
        }
      })
    },
    itemCancel() {
      this.itemOpen = false
    },
    // 删除
    handleDelete() {
      const data = this.detail
      if(this.detail.length == 0) {
        this.$modal.msgWarning('请选择至少一条数据进行删除')
      } else {
        this.$modal.confirm('是否确认删除所选数据项？').then(function () {
          return deleteProject(data)
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => { });
      }
    },

    // 设置阶段
    settingStage(row) {
      console.log(row)
      this.treeData = []
      getByIdTree(row.deptId).then(response => {
        this.treeData = response.data
        this.stageTitle = '设置阶段'
        this.nodeName = undefined
        this.stageOpen = true
        this.stageForm.projectExamplesId = row.projectExamplesId
        this.stageForm.projectId = row.projectId
        this.stageForm.projectCode = row.projectCode
        if(row.phaseId != null) {
          var arr = []
          arr.push(row.phaseId)
          this.$nextTick(() => {
            this.$refs.stageTree.setCheckedKeys(arr);
          })
        } else {
          this.$nextTick(() => {
            this.$refs.stageTree.setCheckedKeys([]);
          })
        }
      })
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.nodeName.indexOf(value) !== -1;
    },
    // 勾选事件
    treeCheck(data, checked) {
      if(data.nodeType != 3) {
        this.$modal.msgWarning('请选择阶段节点')
        this.currentNodekey = '';
        this.expandedkeys = [];
        this.$nextTick(() => {
          this.$refs.stageTree.setCheckedKeys([]);
        })
      }
    },
    selectTreeNode(data, checked, indeterminate) {
      if(checked) {
        if(data.phasesVoList.length == 0 && data.nodeType == 3) {
          this.selectTreeOption = data
          const arr = [data.phaseId]
          this.$refs.stageTree.setCheckedKeys(arr)
        }
      }
    },
    // 保存阶段配置
    submitStage() {
      this.stageForm.phaseId = this.selectTreeOption.phaseId
      this.stageForm.projectPhase = this.selectTreeOption.projectPhase
      saveStage(this.stageForm).then(response=>{
        this.$modal.msgSuccess('设置阶段成功')
        this.stageOpen = false
        this.getList()
      })
    },
    // 关闭阶段设置弹窗
    stageCancel() {
      this.stageOpen = false
    },

    // 设置专业
    settingMajors(row) {
      this.form = {
        deptId: row.deptId,
        projectExamplesId: row.projectExamplesId
      }
      this.majorsForm.projectExamplesId = row.projectExamplesId
      this.majorsForm.projectId = row.projectId
      this.majorsForm.phaseId = row.phaseId
      this.selectOption = []
      this.majorsOptions = []
      getMajors(this.form).then(response=>{
        this.majorsOptions = response.data.all.map(item=> {
          return {
            value: item.majorId,
            label: item.majorName
          }
        })
        var arr = []
        for (let i = 0; i < response.data.select.length; i++) {
          const data = this.majorsOptions.filter(item => item.value == response.data.select[i].majorId)
          arr = arr.concat(data)
        }
        this.selectOption = arr.map(item=>item.value)
        this.majorsTitle = '设置专业'
        this.majorsOpen = true
      })
    },
    // 保存专业设置
    submitMajors() {
      this.majorsForm.majorList = this.selectOption
      saveMajors(this.majorsForm).then(response=>{
        this.$modal.msgSuccess('设置专业成功')
        this.majorsOpen = false
        this.getList()
      })
    },
    // 关闭专业设置弹窗
    majorsCancel() {
      this.majorsOpen = false
    },

    // 分配人员
    settingPersonnel(row) {
      this.form = {
        deptId: row.deptId,
        projectExamplesId: row.projectExamplesId
      }
      this.allocationOpen = true
      this.allocationTitle = '分配人员'
      this.$nextTick(() => {   //此函数执行时所有的DOM挂载和渲染都已完成
        this.$refs.alloctionRef.init(this.form)    //获取子组件中init方法并将父组件数据传递给子组件
      });
    },
    // 关闭设置人员
    closeDelDialog() {
      this.allocationOpen = false
      this.getList()
    },
    // 下发任务
    distributeTasks(row) {
      this.$modal.confirm('是否确认已经分配完各专业的人员，下发任务后将无法分配各专业的人员？点击确认继续下发任务，点击取消继续分配人员。').then(() => {
        deliverATask(row).then(response=>{

          this.$modal.msgSuccess('下发任务成功')
          this.getList()
        })
      }).catch(() => { });
    }
  }
}
</script>

<style scoped>

</style>
